﻿using Syspetro.Core.AppDeal;
using Syspetro.Core.CommandBus;
using Syspetro.Core.Extensions;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;

namespace Syspetro.Core.HttpService
{
    public class HttpCommand : Command
    {
        public string Url { get; set; }
        public HttpMethod HttpMethod { get; set; }
        public Dictionary<string, string> FormParameter = null;
        public string StrParameter = null;
        public Action<HttpRequestHeaders> BuildHeader = null;
    }

    public interface IHttpCommandHandler : ICommandHandler<HttpCommand>
    {

    }
    public class HttpCommandHandler : CommandHandler<HttpCommand>, IHttpCommandHandler
    {
        readonly HttpHelper _httpHelperService;
        public HttpCommandHandler(HttpHelper httpHelperService)
        {
            _httpHelperService = httpHelperService;
        }
        public override SpActionResult<string> Execute(HttpCommand command)
        {
            HttpResponseMessage response;
            if (command.FormParameter != null)
                response = _httpHelperService.HttpRequest(command.Url, command.HttpMethod, command.FormParameter);
            else
                response = _httpHelperService.HttpRequest(command.Url, command.HttpMethod, command.StrParameter);
            return GetResult(response, command.Url, command.FormParameter?.ToString() ?? command.StrParameter);
        }
        private static SpActionResult<string> GetResult(HttpResponseMessage response, string url, string param)
        {
            if (response.IsSuccessStatusCode)
            {
                return response.Content.ReadAsStringAsync().Result.ToObject<SpActionResult<string>>();
            }
            return new SpActionResult<string> { Success = false, Data = $"{url}请求失败;状态码:{response.StatusCode};参数:{param}" };
        }
    }
}
